import { FC, useRef, useState, memo, type Ref } from 'react'
import {useIntersect, Center, MeshWobbleMaterial, MeshReflectorMaterial, DragControls, PivotControls} from '@react-three/drei'
import { Mesh, BufferGeometry, NormalBufferAttributes, Material, Object3DEventMap } from 'three';

/**
 * wobble + 倒影 + DragControls / PivotControls
 * 
 * @param {openPivot: boolean} 是否使用 PivotControls
 */
export const Cube: FC<{openPivot?: boolean}> = ({openPivot = false}) => {
  const ref = useIntersect<any>((visible) => {
    console.log('object is visible', visible)
  })

  const targetMesh = <mesh ref={ref} position={[0, 0.8, 0]}>
    <boxGeometry />
    <MeshWobbleMaterial color={0x3399ee} factor={0.2} speed={7} />
  </mesh>;

  return <>
    <group position={[5, -0.5, 0]}>
      {
        openPivot 
          ? <PivotControls anchor={[1, -1, 1]} scale={0.7}>{targetMesh}</PivotControls>
          : <DragControls>{targetMesh}</DragControls>
      }
      <ReflectPlane />
    </group>
  </>
}

const ReflectPlane = () => <mesh rotation={[-Math.PI / 2, 0, 0]}>
  <planeGeometry args={[50, 50]} />
  <MeshReflectorMaterial
    mirror={0}
    blur={[1390, 1100]}
    resolution={1024}
    mixBlur={1}
    mixStrength={80}
    depthScale={1.2}
    minDepthThreshold={1.4}
    maxDepthThreshold={1.4}
    color="#222222"
    // metalness={0.1}
    // roughness={.1}
  />
</mesh>;